package com.share.strategicMode.task.controller;

import com.share.strategicMode.task.enums.TimeType;
import com.share.strategicMode.task.service.SupportTimeType;
import com.share.strategicMode.task.service.TaskService;
import com.share.strategicMode.task.service.impl.DefaultTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
public class TaskController {
    private Map<TimeType, TaskService> taskServiceMap;
    @Autowired
    private DefaultTaskService defaultService;
    @GetMapping("/task/{timeType}")
    public String customer(@PathVariable("timeType") String timeTypeIn){
        TimeType timeType = TimeType.typeof(timeTypeIn);
        TaskService taskService = taskServiceMap.getOrDefault(timeType, defaultService);
        return taskService.setTask();
    }

    @Autowired
    private void setTaskServiceMap(List<TaskService> taskServices) {
        this.taskServiceMap = taskServices.stream()
                .filter(taskService -> taskService.getClass().isAnnotationPresent(SupportTimeType.class))
                .collect(Collectors.toMap(this::findTimeTypeFromService, Function.identity()));
        if (this.taskServiceMap.size()!=TimeType.values().length-1){
            throw new IllegalArgumentException("有用户类型没有对应的策略");
        }
    }
    private TimeType findTimeTypeFromService(TaskService taskService){
        SupportTimeType annotation = taskService.getClass().getAnnotation(SupportTimeType.class);
        return annotation.value();
    }
}
